package net.xumf.support.security;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import net.xumf.support.utils.CommonUtil;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;

public class RSAUtil {

    private static final String CHARSET = "UTF-8";
    private static final String RSA_ALGORITHM = "RSA";

    /**
     * RSA公钥加密
     *
     * @param str       加密字符串
     * @param publicKey 公钥
     * @return 密文
     * @throws Exception 加密过程中的异常信息
     */
    public static String encrypt(String str, String publicKey) throws Exception {
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(RSA_ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        return Base64.encodeBase64String(cipher.doFinal(str.getBytes(CHARSET)));
    }

    public static void main(String[] args) throws Exception {

        Map<String, Object> params = Maps.newHashMap();
        params.put("GwSignatureNonce", CommonUtil.getSixRandomNumber());
        params.put("GwTimeStamp", System.currentTimeMillis());
        params.put("GwClientId", "d5b10084-d414-4a84-bf78-b0ccecac5176");
        String paramsJSON = JSON.toJSONString(params);
        String encryptStr = encrypt(paramsJSON, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCW1As4reXWjVds93TfKOUO5kLpSkFaNgfQ2auxdL7GYS30cow7R5QsiMkxhxOOHyPzVEn6khSuUMhai6dFqdo3QHmaVkJjeXc9Qx571YwB3jBKX2KGZITvQ5hC4oT2nRSOhAtt9qvXe/rYr8qjBPf+d2AlongHSNqM44guaKG2wQIDAQAB");
        System.out.println(encryptStr);
    }
}
